var hei = 200;
$(function() {
    var dateDom = new Date();
    //获取本地时间，年月日时分
    var year = dateDom.getFullYear();
    var month = dateDom.getMonth() + 1;
    var day = dateDom.getDate();
    var hour = dateDom.getHours();
    var min = dateDom.getMinutes();

    $(".time-line").css("height", hei + "px");

    $(".pub-btn").click(function() {
        var comment_c = $(".input-text-area").val();

        if (comment_c == "") {
            alert("请输入内容");
            return;
        }

        $(".comment-content").prepend("<div class='comment'>" + "<img class=head-shot src='images/photo.jpg'>" +
            "<div class='c-circle'></div>" +
            "<span id='time'>" + year + "-" +
            month + "-" +
            day + "&nbsp;&nbsp;" +
            "<span id='hour'>" + hour + ":" + min + "</span>" +
            "</span>" +
            "<br>" +
            "<p style='padding:4px'>" + comment_c + "</p>" +
            "</div>");
        $(".time-line").css("height", hei + "px");
        hei += 115;
    })


})
layui.use(['laytpl','layer', 'jquery'], function(){
	var laytpl = layui.laytpl;
	var $ = layui.$;
    var layer = layui.layer;
    var testEditor;
	//接收上一个页面的传值
	function getQueryVariable(variable){
	    var query = window.location.search.substring(1);
	    var vars = query.split("&");
	    for (var i=0;i<vars.length;i++) {
	        var pair = vars[i].split("=");
	        if(pair[0] == variable){return pair[1];}
	    }
	    return(false);
	}
	function initData(id,data,getTpl){
		view = document.getElementById(id);
		laytpl(getTpl).render(data, function(html){
		  view.innerHTML = html;
		});
	}
	var dat = {'data':{ //数据
		  "id": 0,
		  "avatar":"./static/images/unLogin.png"
		  ,"name":	"未登录"
}}
	 function intiKMInfo() {
			var user = layui.sessionData('user');
			if(user == null || user == undefined ||$.isEmptyObject(user)){
				user = dat;
				$('#edit').addClass('layui-hide')
				$('#addDiscuss').addClass('layui-hide')
				$('#updataBtn').addClass('layui-hide')
				$('#like').addClass('layui-hide')
			}
			var getTpl = person.innerHTML
			initData('account',user,getTpl);
			//加载分类
            $.ajax({
                type: "GET",
                url: "http://127.0.0.1:8080/blog/category/categoryTypeList",
                success: function (data) {   
                	var res = { //数据
					  "data":{'categoryList':[
						  {
							  'id':1,
							  content:'PHP'
							  },
						  {
							  'id':2,
							  content:'Java'}]}
					}
                	var rs = JSON.parse(data);
                	console.log(rs)
                	var getTpl = category.innerHTML
                	if(rs.data!=null){
                		initData('categoryList',rs.data.data,getTpl);
                	}else{
                		initData('categoryList',res.data.data.list,getTpl);
                	}
                	layui.data('category', {
                		  key: 'categoryList'
                		  ,value: rs.data.data.list
                		});
                }
            });
          //加载文章
            $.ajax({
                type: "GET",
                url: "http://127.0.0.1:8080/blog/article/article",
                data:{
                	id: getQueryVariable('id'),
                },
                success: function (data) {
                	var rs = JSON.parse(data);
                	if((!$.isEmptyObject(user)) && (!$.isEmptyObject(rs.data.data)) && parseInt(user.data.id) != parseInt(rs.data.data.userId)){
                		$('#updataBtn').addClass('layui-hide')
                	}
                	var getTpl = article.innerHTML
                	var getTp = articleBottom.innerHTML
                	var discussTpl = discuss.innerHTML
                	if(rs.data!=null){
                		initData('articleView',rs.data,getTpl);
                		initData('articleBottomView',rs.data,getTp);
                		initData('discussView',rs.data,discussTpl);
                	}else{
                		initData('articleView',null,getTpl);
                		initData('articleBottomView',rs.data,getTp);
                	}
                	layui.data('article', {
                		  key: 'data'
                		  ,value: rs.data.data
                		});
                  //markDown转HTMl的方法
                    function mdToHml(){
                        //先对容器初始化，在需要展示的容器中创建textarea隐藏标签，
                        $("#markdownToHTML").html('<textarea id="content" style="display:none;"></textarea>');
                        var content=rs.data.data.code;//获取需要转换的内容
                        $("#content").val(content);//将需要转换的内容加到转换后展示容器的textarea隐藏标签中

                        //转换开始,第一个参数是上面的div的id
                        editormd.markdownToHTML("markdownToHTML", {
                            htmlDecode: "style,script,iframe", //可以过滤标签解码
                            emoji: true,
                            taskList:true,
                            tex: true,               // 默认不解析
                            flowChart:true,         // 默认不解析
                            sequenceDiagram:true,  // 默认不解析
                        }); 
                    }
                    mdToHml()
                }
            });
        }
		intiKMInfo();
        $('#logout').on('click',function(){
        	layui.sessionData('user',{
        		key:'data',
        		remove: true
        	})
        	layer.msg("注销成功！")
        	window.location.href="./index.html"
        })
        $('#showEditor').on('click', function(){
        	var data = layui.data('article').data;
        	console.log()
        	var url="./editor.html?id="+getQueryVariable('id')
        	window.location.href = url;
		});
        //点赞功能
        $('#like').on('click',function(){
        	var user = layui.sessionData('user');
        	
        	var data = {
	        		'id': layui.data('article').data.id,
	        		'likeCount': parseInt(layui.data('article').data.likeCount)+1,
    				}
        	$.ajax({
    	        type: "POST",
    	        contentType:"application/json;charset=utf-8",
    	        url: "http://127.0.0.1:8080/blog/article/article",
    	        data:JSON.stringify(data),
    	        success: function (data) {
    	        	var rs = JSON.parse(data);
    	        	if(rs.code == 200){
    	        		layer.msg('点赞成功！')
    	        		window.location.reload();
    	        		
    	        	}
    	        	
    	        }
       		 }); 
        })
        //评论功能
        $('#addDiscussContent').on('click',function(){
        	var data = {
	        		'content': $('#discussContent').val(),
	        		'articleId': layui.data('article').data.id,
	        		'userId': layui.sessionData("user").data.id
    				}
        	if($.isEmptyObject(data.content)){
        		layer.msg('不能发表空评论！');
        		return false;
        	}
        	$.ajax({
    	        type: "POST",
    	        contentType:"application/json;charset=utf-8",
    	        url: "http://127.0.0.1:8080/blog/discuss/discuss",
    	        data:JSON.stringify(data),
    	        success: function (data) {
    	        	var rs = JSON.parse(data);
    	        	if(rs.code == 200){
    	        		layer.open({
  	        			  content: "是否确认评论？",
  	        			  yes: function(index, layero){
  	        				    window.location.reload();
  	        				  }
  	        			});
    	        		
    	        	}
    	        	
    	        }
       		 });
        })
             
    }); 